package org.boulderfoodrescue.webapp.client.old.event;

import com.google.gwt.event.shared.GwtEvent;

public class ViewClosedEvent<T> extends GwtEvent<ViewClosedHandler<T>> {

  /**
   * Handler type.
   */
  private static Type<ViewClosedHandler<?>> TYPE;

  /**
   * Fires a close event on all registered handlers in the handler manager. If
   * no such handlers exist, this method will do nothing.
   * 
   * @param <T> the target type
   * @param source the source of the handlers
   * @param result the result generated by the view that should be passed to its parent
   */
  public static <T> void fire(HasViewClosedHandlers<T> source, T result) {
  	if (TYPE != null) {
      ViewClosedEvent<T> event = new ViewClosedEvent<T>(result);
      source.fireEvent(event);
    }
  }

  /**
   * Gets the type associated with this event.
   * 
   * @return returns the handler type
   */
  public static Type<ViewClosedHandler<?>> getType() {
    return TYPE != null ? TYPE : (TYPE = new Type<ViewClosedHandler<?>>());
  }

  private final T closeResult;

  /**
   * Creates a new close event.
   * 
   * @param target the target
   * @param autoClosed whether it is auto closed
   */
  protected ViewClosedEvent(T target) {
    this.closeResult = target;
  }

  // The instance knows its of type T, but the TYPE
  // field itself does not, so we have to do an unsafe cast here.
  @SuppressWarnings("unchecked")
  @Override
  public final Type<ViewClosedHandler<T>> getAssociatedType() {
    return (Type) TYPE;
  }

  /**
   * Gets the close result.
   * 
   * @return the closeResult
   */
  public T getCloseResult() {
    return closeResult;
  }

  @Override
  protected void dispatch(ViewClosedHandler<T> handler) {
    handler.onViewClosed(this);
  }
}
